import { z } from "zod";
import db from "@/server/connector/db";
import _ from "lodash";
import { CONTENT_TYPE_ZOD, CONTENT_ZOD, PERSONAL_ZOD, TITLE_ZOD } from "@/shared/restrictions/post";
import { wrapRoute } from "@/server/wrapper";
import { getSessionFromRequest } from "@/server/service/session-service";

const POST_PAYLOAD_TYPES = z.object({
  contentType: CONTENT_TYPE_ZOD,
  content: CONTENT_ZOD,
  title: TITLE_ZOD,
  personal: PERSONAL_ZOD,
});

export async function POST(req: Request): Promise<Response> {
  return await wrapRoute(async (): Promise<{ postId: string }> => {
    const session = await getSessionFromRequest(req)
    const me = await session.getMe()
    const { contentType, content, title, personal } = POST_PAYLOAD_TYPES.parse(await req.json());
    const post = await db.post.create({
      data: {
        title,
        contentType,
        content,
        personal,
        deleteTime: null,
        createTime: new Date(),
        updateTime: new Date(),
        authorId: me.id,
      },
    });
    return { postId: post.id };
  });
}
